<?php
namespace Cust\Controller;
use Common\Controller\CommonController;

/**
 * 用户模块
 */
class CustController extends CommonController {
	
	private $custFields = array('nickname','realname','firstname','secondname','sex','birthday','email','age','country','area','address','hometown','signature','description');
	private $custExtFields = array('university','school','majorclass','entranceyear','sdtno','qq','contact','contactmobile','iskitchener','dishes','videourl');
	
	protected function _initialize(){
		parent::_initialize();
		$this->_mycache = S(C('REDIS_DSN'));
		$this->_auth();
		
		$this->_moduleid = 101;
		$this->_cust = new \Common\Model\CustModel();
		$this->_cust_ext = new \Common\Model\CustExtModel();
	}
	
	
	/**
	 * 获取服务器信息
	 */
	public function getServerAction(){
		$ip = I('request.ip');
		$logintype = (int)I('request.logintype');
		$this->_getServer($logintype,$ip);
	}
	
	private function _getServer($logintype,$ip=""){
		if($logintype != 1 && $logintype != 2){
			$this->status = 1001;
			$this->msg = L('STATUS_1001');
			$this->outPut();
		}
		
		if(empty($ip)){
			$ip = \tools::getClientIp();
		}
		
		//获取聊天服务器地址和端口
		$talkInfo = \im::getTalkServer($this->_custInfo['custid'],$logintype,'',$ip);
		if($logintype == 2) $talkInfo['port'] = "6999";
		$returnData['chat']['host'] = (string)$talkInfo['ip'];
		$returnData['chat']['port'] = (string)$talkInfo['port'];
	
		//视频服务器地址
		$webRtcRoom = C('WEBRTC_ROOM_SERVER');
		$roomIdx = \tools::talkCacheHash($this->_custInfo['custid'] , count($webRtcRoom));
		$returnData['roomserver'] = $webRtcRoom[$roomIdx];
			
		$this->data = $returnData;
		$this->outPut();
	}
	
    
	/**
	 * 查找用户
	 */
    public function searchAction(){
		$username = I('request.username');
		$this->_search($username);
    }
    
    private function _search($username){
    	if(empty($username)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	 
    	//定义查找用户时需要的字段
    	$fields = array('custid','nickname','status','sex');
    	$custInfo = $this->_cust->searchCustInfo($username);
    	if(!empty($custInfo)){
    		$returnData = array();
    		foreach($custInfo as $k=>$v){
    			$returnData[$k]['custid'] = $v['custid'];
    			$returnData[$k]['nickname'] = $v['nickname'];
    			$returnData[$k]['status'] = $v['status'];
    			$returnData[$k]['sex'] = $v['sex'];
    		}
    		$this->data = $returnData;
    		$this->outPut();
    	}else{
    		$this->status = 1113;
    		$this->msg = L('STATUS_1113');
    		$this->outPut();
    	}
    }
    
    
    /**
     * 获取用户列表
     */
    public function getCustListAction(){
    	$pageIndex = (int)I('request.pageIndex');
    	$pageSize = (int)I('request.pageSize');
    	$keywords = I('request.keywords');
    	$this->_getCustList($keywords , $pageIndex , $pageSize);
    }
    
    private function _getCustList($keywords , $pageIndex , $pageSize){
		if($pageIndex)$pageIndex--;
		$data['pageIndex'] = $pageIndex;
		$data['pageSize'] = $pageSize;
		$data['searchKey'] = $keywords;
		$custList = $this->_cust->getCustList($data);
		
		$this->data = $custList;
		$this->outPut();
    }
    
    
    /**
     * 获取目标用户部分信息
     */
    public function getCustSimpleInfoAction(){
    	$custid = (int)I('request.custid');
    	$fields = array('custid','nickname','realname','pinyinname','_isfriend','_nickname','_phonenumber','_memo','status','sex','birthday','mobile','email','age','area','idenum','hometown','sdtno','majorclass','signature');
    	$this->_getCustInfomation($custid,true,$fields);
    }
    
    protected function _getCustInfomation($custid , $apiReturn = true , $fields = array()){
    	if(empty($custid)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	 
    	$custInfo = $this->_getCustInfo($custid);
    	 
    	if(!empty($custInfo)){
    		$returnData = array();
    		if(!empty($fields)){
    			foreach($custInfo as $k=>$v){
    				if(in_array($k , $fields)){
    					$returnData[$k] = $v;
    				}
    			}
    		}else{
    			$returnData = $custInfo;
    		}
    		
    		$returnData['_isfriend'] = "0";
    		$returnData['_nickname'] = "";
    		$returnData['_phonenumber'] = "";
    		$returnData['_memo'] = "";
    		if($custid != $this->_custInfo['custid']){
    			$friendInfo = $this->_checkFriend($custid);//判断是否是自己的好友
    			if(!empty($friendInfo)){
    				$returnData['_isfriend'] = "1";
    				$returnData['_nickname'] = $friendInfo['nickname'];
    				$returnData['_phonenumber'] = $friendInfo['phonenumber'];
    				$returnData['_memo'] = $friendInfo['memo'];
    			}
    		}
    		
    		
    		//判断是否是自己的同事
    		$returnData['_isworkmate'] = "0";
    		if(empty($this->_ent)) $this->_ent = new \Common\Model\EntModel();
    		$myEntList = $this->_ent->getAllEntByCust($this->_custInfo['custid']);
    		$custEntList = $this->_ent->getAllEntByCust($custid);
    		if(!empty($myEntList) && !empty($custEntList)){
    			$tmp = array();
    			foreach($myEntList as $myent){
    				$tmp[$myent['entid']] = 1;
    			}
    			
    			foreach($custEntList as $custent){
    				if($tmp[$custent['entid']] == 1){
    					$returnData['_isworkmate'] = "1";
    					break;
    				}
    			}
    		}
    		
    		
    		
    		if(!$apiReturn) return $returnData;
    
    		$this->data = $returnData;
			$this->outPut();
    	}else{
    		$this->status = 1113;
    		$this->msg = L('STATUS_1113');
    		$this->outPut();
    	}
    }
    
    
    private function _checkFriend($custid){
    	if(empty($this->_friend)){
    		$this->_friend = new \Common\Model\FriendModel();
    	}
    	$data['custid'] = $this->_custInfo['custid'];
    	$data['tcustid'] = $custid;
    	$result = $this->_friend->getFriend($data);
    	if(!empty($result))
    		return $result;
    	else 
    		return false;
    }
    
    
    /**
     * 获取用户信息
     */
    public function getCustInfoAction(){
    	$this->_getCustInfomation($this->_custInfo['custid'] , true);
    }
    
    
    /**
     * 按字段保存用户信息
     */
    public function saveCustInfoByFieldAction(){
    	$field = I('request.field');
    	$value = I('request.value');
    	$this->_saveCustInfoByField($this->_custInfo['custid'],$field,$value);
    }
    
    protected function _saveCustInfoByField($custid,$field,$value){
    	if(empty($custid) || empty($field)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	 
    	//设置保存到qyx_cust的字段
    	if(in_array($field , $this->custFields)){
    		$arr = array();
    		$arr['custid'] = $custid;
    		$arr[$field] = $value;
    		if($field == "nickname"){
    			$arr['pinyinname'] = \pinyin::toPingyin($value);
    			$this->_custInfo['nickname'] = $value;
    		}
    
    		$ret = $this->_cust->updateCust($arr);
    		
    		if($ret == -1){
    			$this->status = 1116;
    			$this->msg = L('STATUS_1116');
    			$this->outPut();
    		}
    	}
    	
    	if(in_array($field , $this->custExtFields)){
    		$arr = array();
    		$arr['custid'] = $custid;
    		$arr[$field] = $value;
    		
    		$ret = $this->_cust_ext->saveCustExt($arr);
    	}
    	
    	
    	if($ret){
    		//if($field == "birthday")$arr['age'] = \tools::getAge($value);
    		$this->_setCustInfoCache($arr);
    		
    		//$friendList = $this->_getFriendListCache($custid);
    		$friendList = $this->_getFriendList($custid);
    		if(!empty($friendList)){
    			foreach($friendList as &$friend){
    				$this->_delFriendListCache($friend['custid']);
    				$friends[] = $friend['custid'];
    			}
    			
    			
    			//系统消息
    			$msg['from_cust_name'] = $this->_custInfo['nickname'];
    			$msg['from_cust_id'] = $this->_custInfo['custid'];
    			$msg['cust_id'] = $this->_custInfo['custid'];
    			$msg['type'] = 18;
    			$msg['content'] = "";
    			\im::sendMsg(3, $friends, array(), $msg);
    		}
    		 
    		$this->outPut();
    	}else{
    		$this->status = 1120;
    		$this->msg = L('STATUS_1120');
    		$this->outPut();
    	}
    }
    
    
    /**
     * 设置用户头像
     */
    public function setCustAvatarAction(){
    	$this->_setCustAvatar();
    }
    
    private function _setCustAvatar(){
    	$filedata = $_FILES['uploadedFile']['name'];
        $errorNo = $_FILES['uploadedFile']['error'];
        if($errorNo){
    		$this->_getUploadError($errorNo);
    	}
    	
    	if(!empty($filedata)){
    		$mimetype = strtolower($_FILES['uploadedFile']['type']);
    		$res = \tools::makeAvatarFilePath(C('CUST_AVATAR_PATH') , $this->_custInfo['custid'] , $mimetype);
    		$filetarget = $res['filetarget'];
    		$targetpath = $res['targetpath'];
    		$width = $res['width'];
    		$height = $res['height'];
    
    		\tools::delAllFile($targetpath);
    		 
    		$ret = move_uploaded_file($_FILES['uploadedFile']['tmp_name'], $filetarget);
    		if($ret){
    			$arr = array();
    			$arr['custid'] = $this->_custInfo['custid'];
    			$arr['avatar'] = $filetarget;
    			$this->_cust->updateCust($arr);

    			$friendList = $this->_getFriendList($this->_custInfo['custid']);
    			if(!empty($friendList)){
    				foreach($friendList as $friend){
    					$friends[] = $friend['custid'];
    				}
    				
    				//系统消息
    				$msg['from_cust_name'] = $this->_custInfo['nickname'];
    				$msg['from_cust_id'] = $this->_custInfo['custid'];
    				$msg['cust_id'] = $this->_custInfo['custid'];
    				$msg['type'] = 14;
    				$msg['content'] = "";
    				\im::sendMsg(3, $friends, array(), $msg);
    			}
    			
    			$this->data = array('width'=>$width,'height'=>$height);
    			$this->outPut();
    		}else{
    			$this->status = 1129;
    			$this->msg = L('STATUS_1129');
    			$this->outPut();
    		}
    	}
    }
    
    
    /**
     * 获取用户二维码
     */
    public function getCustQRCodeAction(){
    	$this->_getCustQRCode();
    }
    
    private function _getCustQRCode(){
    	$data['custid'] = $this->_custInfo['custid'];
    	$data['nickname'] = $this->_custInfo['nickname'];
    	$data['status'] = $this->_custInfo['status'];
    	$data['controller'] = CONTROLLER_NAME;
    	//$data = CONTROLLER_NAME . "://" . json_encode($data);
    	$data = C('QR_CODE_INFO_URL') . "?data=" . \aes::encrypt(json_encode($data) , C('TOKEN_SALT'));

    	$qrcodefile = "/tmp/cust_{$this->_custInfo['custid']}.png";
    	$logofile = "";//准备好的用户avatar图片地址或图片url
    	
    	\tools::makeQrcode($data , $qrcodefile , $logofile);
    }
    
    
    /**
     * 修改密码
     */
    public function updatePwdAction(){
    	$oldpassword = I('request.oldpassword');
    	$newpassword = I('request.newpassword');
    	$passwordconfirm = I('request.passwordconfirm');
    	$this->_updatePwd($oldpassword,$newpassword,$passwordconfirm);
    }
    
    private function _updatePwd($oldpassword,$newpassword,$passwordconfirm){
    	if(empty($oldpassword) || empty($newpassword) || empty($passwordconfirm) || $newpassword != $passwordconfirm){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	 
    	$custInfo = $this->_cust->getCustInfoById($this->_custInfo['custid']);
    	if(!\tools::verifyPwd($oldpassword , $custInfo['password'])){
    		$this->status = 1153;
    		$this->msg = L('STATUS_1153');
    		$this->outPut();
    	}
    
    	$arr = array();
    	$arr['custid'] = $this->_custInfo['custid'];
    	$arr['password'] = \tools::encodePwd($newpassword);
    	$ret = $this->_cust->updateCust($arr);
    	if($ret){
    		$this->outPut();
    	}else{
    		$this->status = 1114;
    		$this->msg = L('STATUS_1114');
    		$this->outPut();
    	}
    }
    
    
    /**
     * 修改账户信息
     */
    public function updateAccountAction(){
    	$username = I('request.username');
    	$password = I('request.newpassword');
    	$vercode = I('request.vercode');
    	$time = I('request.time');
    	$sign = I('request.sign');
    	$regtype = I('request.regtype');
    	$this->_updateAccount($username,$password,$vercode,$time,$sign,$regtype);
    }
    
    private function _updateAccount($username,$password,$vercode,$time,$sign,$regtype=1){
    	$regtype = empty($regtype) ? 1 : $regtype;
    	if(empty($username) || empty($password) || empty($vercode) || empty($time) || empty($sign) || !in_array($regtype , array(1,2,3))){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	
    	$this->_checkVerCode($username , $vercode , $regtype);
    	
    	$this->_checkSign($username,$time,$sign);
    	
    	$this->_cust->startTrans();
    	
    	$arr = array();
    	if($regtype == 1){
    		if(!\validate::isMobilePhoneNumber($username)){
    			$this->status = 1118;
    			$this->msg = L('STATUS_1118');
    			$this->outPut();
    		}
    		$arr['mobile'] = $username;//手机号注册
    		$ret1 = $this->_cust->emptyCustMobile($username);
    	}else{
    		if(!\validate::isEmail($username)){
    			$this->status = 1117;
    			$this->msg = L('STATUS_1117');
    			$this->outPut();
    		}
    		$arr['email'] = $username;//邮箱注册
    		$ret1 = $this->_cust->emptyCustEmail($username);
    	}
    	$arr['custid'] = $this->_custInfo['custid'];
    	$arr['password'] = \tools::encodePwd($password);
    	$ret2 = $this->_cust->updateCust($arr);
    	if($ret1 && $ret2){
    		$this->_cust->commit();
    		$this->_setCustInfoCache($arr);
    		$this->outPut();
    	}else{
    		$this->_cust->rollback();
    		$this->status = 1119;
    		$this->msg = L('STATUS_1119');
    		$this->outPut();
    	}
    }
    
    
    /**
     * 消息提醒设置
     */
    public function msgSettingAction(){
    	$shock = (int)I('request.shock');
    	$beep = (int)I('request.beep');
    	$push = (int)I('request.push');
    
    	$this->_msgSetting($shock , $beep , $push);
    }
    
    private function _msgSetting($shock , $beep , $push){
    	$msgsetting = array('shock'=>(string)$shock , 'beep'=>(string)$beep , 'push'=>(string)$push);
    	$custInfo['custid'] = $this->_custInfo['custid'];
    	$custInfo['msgsetting'] = json_encode($msgsetting);
    	
    	if(empty($this->_cust_ext)) $this->_cust_ext = new \Common\Model\CustExtModel();
    	$ret = $this->_cust_ext->saveCustExt($custInfo);
    	if($ret){
    		if($beep <= 0)
    			$this->_mycache->srem(\cachekey::$key['BASE_KEY_CONF']['NO_SOUND_CUSTS'], $this->_custInfo['custid']);
    		else
    			$this->_mycache->sadd(\cachekey::$key['BASE_KEY_CONF']['NO_SOUND_CUSTS'], $this->_custInfo['custid']);
    		
    		if($push <= 0)
    			$this->_mycache->srem(\cachekey::$key['BASE_KEY_CONF']['NO_PUSH_CUSTS'], $this->_custInfo['custid']);
    		else
    			$this->_mycache->sadd(\cachekey::$key['BASE_KEY_CONF']['NO_PUSH_CUSTS'], $this->_custInfo['custid']);
    		
    		$this->_setCustInfoCache($custInfo);
    		$this->outPut();
    	}else{
    		$this->status = 1125;
    		$this->msg = L('STATUS_1125');
    		$this->outPut();
    	}
    }
    
	
    /**
     * 获取通知
     */
    public function getNoticeListAction(){
    	$moduleid = (int)I('request.moduleid');
    	$status = (int)I('request.status');
    	$this->_getNoticeList($moduleid , $status);
    }
    
    private function _getNoticeList($moduleid , $status){
    	$data['tcustid'] = $this->_custInfo['custid'];
    	$data['moduleid'] = (int)$moduleid;
    	$data['status'] = (int)$status;
    	$noticeList = $this->_getNotices($data);
    	if($noticeList){
    		$this->data = $noticeList;
    		$this->outPut();
    	}else{
    		$this->status = 1021;
    		$this->msg = L('STATUS_1021');
    		$this->outPut();
    	}
    }
    
    
    /**
     * 处理通知
     */
    public function processNoticeAction(){
    	$noticeids = I('request.noticeids');
    	$status = (int)I('request.status');
    	$this->_processNotice($noticeids , $status);
    }
    
    private function _processNotice($noticeids , $status){
    	if(empty($noticeids)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	$noticeids = explode(",", $noticeids);
    	
    	$data['noticeids'] = $noticeids;
    	$data['tcustid'] = $this->_custInfo['custid'];
    	$data['status'] = (int)$status;
    	$ret = $this->_updateNotice($data);
    	if($ret){
    		$this->outPut();
    	}else{
    		$this->status = 1023;
    		$this->msg = L('STATUS_1023');
    		$this->outPut();
    	}
    }
    
    
    /**
     * 根据手机号/邮箱发邀请注册短信/邮件
     */
    public function invitRegisterAction(){
    	$username = I('request.username');
    	$time = I('request.time');
    	$sign = I('request.sign');
    	$regtype = I('request.regtype');
    	$this->_invitRegister($username , $time , $sign , $regtype);
    }
    
    
    private function _invitRegister($username , $time , $sign , $regtype=1){
    	$regtype = empty($regtype) ? 1 : $regtype;
    	if(empty($username) || empty($time) || empty($sign)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	 
    	$custInvitKey = \cachekey::$key['BASE_KEY_CONF']['CUST_REGISTER_INVIT'].$this->_custInfo['custid'].":".$username;
    	$invited = $this->_mycache->get($custInvitKey);
    	if(empty($invited)){//从未邀请过就发短信邀请
    		$this->_mycache->set($custInvitKey , $username);
    
    		if(!\validate::isMobilePhoneNumber($username)){
    			$this->status = 1118;
    			$this->msg = L('STATUS_1118');
    			$this->outPut();
    		}
    
    		$this->_checkSign($username,$time,$sign);
    		//TODO
    		/* $content = "xxx邀请您注册xxx";
    		if($regtype == 1){
    			\sms::yuntongxun($username, array($username , $content), 53038);//53038 , 50530
    		}else{ 
    			\tools::send_mail($username, "", "title", $content);
    		} */
    	}
    	 
    	$this->outPut();
    }
    
    
    public function getAllMsgSettingAction(){
    	$this->data = $this->_getAllMsgSetting($this->_custInfo['custid']);
    	$this->outPut();
    }
    
    
    //更新用户信息
    public function updateCustInfoAction(){
    	$custinfo = I('request.custinfo');
    	$this->_updateCustInfo($custinfo);
    }
    
    private function _updateCustInfo($custinfo){
    	if(empty($custinfo)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	
    	$custinfo = json_decode($custinfo , true);
    	if(empty($custinfo)){
    		$this->status = 1000;
    		$this->msg = L('STATUS_1000');
    		$this->outPut();
    	}
    	$custinfo['custid'] = $this->_custInfo['custid'];
    	
    	$data = array();
	    foreach($custinfo as $key=>$val){
	    	if(in_array($key , $this->custFields)){
	    		$data[$key] = $val;
	    	}
	    	
	    	if($key == "nickname"){
	    		$data['pinyinname'] = \pinyin::toPingyin($val);
	    		$this->_custInfo['nickname'] = $val;
	    	}
	    }
    	$data['custid'] = $this->_custInfo['custid'];
    	$ret1 = $this->_cust->updateCust($data);
    	
    	
    	$data = array();
    	foreach($custinfo as $key=>$val){
    		if(in_array($key , $this->custExtFields)){
    			if($key == "entranceyear") $val = date("Y-m-d" , strtotime($val));
    			$data[$key] = $val;
    		}
    	}
    	$data['custid'] = $this->_custInfo['custid'];
    	$ret2 = $this->_cust_ext->saveCustExt($data);
    	
    	if($ret1 || $ret2){
    		//if($field == "birthday")$custinfo['age'] = \tools::getAge($value);
    		$this->_setCustInfoCache($custinfo);
    		 
    		$friendList = $this->_getFriendList($this->_custInfo['custid']);
    		//$friendList = $this->_getFriendListCache($this->_custInfo['custid']);
    		if(!empty($friendList)){
    			foreach($friendList as &$friend){
    				$this->_delFriendListCache($friend['custid']);
    				$friends[] = $friend['custid'];
    			}
    			
    			
    			//系统消息
    			$msg['from_cust_name'] = $this->_custInfo['nickname'];
    			$msg['from_cust_id'] = $this->_custInfo['custid'];
    			$msg['cust_id'] = $this->_custInfo['custid'];
    			$msg['type'] = 18;
    			$msg['content'] = "";
    			\im::sendMsg(3, $friends, array(), $msg);
    		}
    		
    		$this->outPut();
    	}else{
    		$this->status = 1120;
    		$this->msg = L('STATUS_1120');
    		$this->outPut();
    	}
    }
}
